package com.example.petshopping.ui.profile;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.petshopping.R;
import com.example.petshopping.model.AppMemberUserInfoRespVO;
import com.example.petshopping.model.AppMemberUserUpdateReqVO;
import com.example.petshopping.model.CommonResult;
import com.example.petshopping.network.RetrofitClient;
import com.example.petshopping.utils.UserInfoManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserInfoActivity extends AppCompatActivity {

    private static final String TAG = "UserInfoActivity";
    private static final int PERMISSION_REQUEST_CODE = 100;
    
    private ImageView btnBack;
    private TextView btnSave;
    private CardView cardAvatar;
    private ImageView ivAvatar;
    private EditText etNickname;
    private View layoutGender;
    private TextView tvGender;
    private View layoutBirthday;
    private TextView tvBirthday;

    private Calendar calendar;
    private String[] genderOptions = {"保密","男", "女"};
    private int selectedGender = 0; // 默认选择男
    
    // 图片选择器
    private ActivityResultLauncher<Intent> imagePickerLauncher;
    private ActivityResultLauncher<Intent> cameraLauncher;
    private ActivityResultLauncher<String> permissionLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        initViews();
        initActivityResultLaunchers();
        loadUserInfo();
        setupClickListeners();
    }

    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        btnSave = findViewById(R.id.btn_save);
        cardAvatar = findViewById(R.id.card_avatar);
        ivAvatar = findViewById(R.id.iv_avatar);
        etNickname = findViewById(R.id.et_nickname);
        layoutGender = findViewById(R.id.layout_gender);
        tvGender = findViewById(R.id.tv_gender);
        layoutBirthday = findViewById(R.id.layout_birthday);
        tvBirthday = findViewById(R.id.tv_birthday);


        calendar = Calendar.getInstance();
    }
    
    /**
     * 初始化ActivityResultLauncher
     */
    private void initActivityResultLaunchers() {
        // 图片选择器
        imagePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                            Uri selectedImageUri = result.getData().getData();
                            if (selectedImageUri != null) {
                                handleSelectedImage(selectedImageUri);
                            }
                        }
                    }
                }
        );
        
        // 相机拍照
        cameraLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK) {
                            // TODO: 处理拍照结果
                            Toast.makeText(UserInfoActivity.this, "拍照功能开发中", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
        );
        
        // 权限请求
        permissionLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        openImagePicker();
                    } else {
                        Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }

    private void loadUserInfo() {
        // 首先从网络获取最新用户信息（异步）
        fetchUserInfoFromNetwork();
        
        // 同时加载本地缓存的信息作为初始显示
        loadLocalUserInfo();
    }
    
    /**
     * 从网络获取用户信息
     */
    private void fetchUserInfoFromNetwork() {
        RetrofitClient.getInstance().getApiService().getUserInfo()
                .enqueue(new Callback<CommonResult<AppMemberUserInfoRespVO>>() {
                    @Override
                    public void onResponse(Call<CommonResult<AppMemberUserInfoRespVO>> call, Response<CommonResult<AppMemberUserInfoRespVO>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            CommonResult<AppMemberUserInfoRespVO> result = response.body();
                            if (result.isSuccess() && result.getData() != null) {
                                // 获取用户信息成功，保存并更新UI
                                AppMemberUserInfoRespVO userInfo = result.getData();
                                UserInfoManager.saveUserInfo(UserInfoActivity.this, userInfo);
                                
                                // 更新UI显示
                                updateUserInfoDisplay(userInfo);
                                
                                Log.d(TAG, "从网络获取用户信息成功");
                            } else {
                                Log.w(TAG, "获取用户信息失败: " + result.getMsg());
                                Toast.makeText(UserInfoActivity.this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Log.w(TAG, "获取用户信息网络请求失败");
                            Toast.makeText(UserInfoActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<CommonResult<AppMemberUserInfoRespVO>> call, Throwable t) {
                        Log.e(TAG, "获取用户信息网络请求失败", t);
                        Toast.makeText(UserInfoActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                        // 网络请求失败时，继续使用本地缓存的信息
                    }
                });
    }
    
    /**
     * 加载本地用户信息
     */
    private void loadLocalUserInfo() {
        // 从本地存储加载用户信息
        AppMemberUserInfoRespVO userInfo = UserInfoManager.getUserInfo(this);
        
        if (userInfo != null) {
            updateUserInfoDisplay(userInfo);
        } else {
            // 如果没有用户信息，使用默认值
            etNickname.setText(UserInfoManager.getUserNickname(this));
            
            // 设置默认性别
            tvGender.setText("男");
            
            // 尝试加载保存的头像URL
            loadAvatar(UserInfoManager.getUserAvatar(this));
        }
        
        // 生日始终使用模拟数据（后端暂未支持）
        tvBirthday.setText("1995-06-15");
    }
    
    /**
     * 更新用户信息显示
     */
    private void updateUserInfoDisplay(AppMemberUserInfoRespVO userInfo) {
        // 设置用户昵称
        if (userInfo.getNickname() != null && !userInfo.getNickname().isEmpty()) {
            etNickname.setText(userInfo.getNickname());
        } else {
            etNickname.setText("用户" + (userInfo.getId() != null ? userInfo.getId() : ""));
        }
           
        // 设置用户生日
        if (userInfo.getBirthday() != null && !userInfo.getBirthday().isEmpty()) {
            tvBirthday.setText(userInfo.getBirthday());
        } else {
            tvBirthday.setText("1990-01-01");
        }

        // 设置性别
        if (userInfo.getSex() != null) {
            String genderText;
            switch (userInfo.getSex()) {
                case 1:
                    genderText = "男";
                    selectedGender = 1;
                    break;
                case 2:
                    genderText = "女";
                    selectedGender = 2;
                    break;
                default:
                    genderText = "保密";
                    selectedGender = 0;
                    break;
            }
            tvGender.setText(genderText);
        } else {
            tvGender.setText("男");
            selectedGender = 1;
        }
        
        // 加载用户头像
        loadAvatar(userInfo.getAvatar());
     
    }
    
    /**
     * 加载用户头像
     * @param avatarUrl 头像URL，可能为空
     */
    private void loadAvatar(String avatarUrl) {
        if (avatarUrl != null && !avatarUrl.isEmpty()) {
            // 使用Glide加载网络头像
            Glide.with(this)
                    .load(avatarUrl)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .placeholder(R.drawable.cat) // 加载中显示默认头像
                    .error(R.drawable.cat) // 加载失败显示默认头像
                    .into(ivAvatar);
        } else {
            // 如果没有头像URL，使用默认头像
            ivAvatar.setImageResource(R.drawable.cat);
        }
    }

    private void setupClickListeners() {
        // 返回按钮
        btnBack.setOnClickListener(v -> finish());

        // 保存按钮
        btnSave.setOnClickListener(v -> saveUserInfo());

        // 头像点击
        cardAvatar.setOnClickListener(v -> changeAvatar());

        // 性别选择
        layoutGender.setOnClickListener(v -> showGenderDialog());

        // 生日选择
        layoutBirthday.setOnClickListener(v -> showDatePicker());
    }

    private void saveUserInfo() {
        // 设置昵称
        String nickname = etNickname.getText().toString().trim();
        
        if (nickname.isEmpty()) {
            Toast.makeText(this, "昵称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (nickname.length() > 30) {
            Toast.makeText(this, "昵称不能超过30个字符", Toast.LENGTH_SHORT).show();
            return;
        }

        // 设置生日
        String birthday = tvBirthday.getText().toString();

        // 获取当前的用户信息
        AppMemberUserInfoRespVO userInfo = UserInfoManager.getUserInfo(this);
        if (userInfo == null) {
            userInfo = new AppMemberUserInfoRespVO();
        }
        
        // 更新用户信息
        userInfo.setNickname(nickname);
        userInfo.setBirthday(birthday); 

        // 设置性别（将显示文本转换为数字）
        String genderText = tvGender.getText().toString();
        switch (genderText) {
            case "男":
                userInfo.setSex(1);
                break;
            case "女":
                userInfo.setSex(2);
                break;
            default:
                userInfo.setSex(0);
                break;
        }
        
        // 保存到本地存储
        UserInfoManager.saveUserInfo(this, userInfo);
        
        // 保存到服务器
        saveUserInfoToServer(userInfo);
    }

    private void changeAvatar() {
        // 显示头像选择对话框
        String[] options = {"从相册选择", "拍照", "使用默认头像"};
        
        new AlertDialog.Builder(this)
                .setTitle("更换头像")
                //设置对话框圆角
                .setItems(options, (dialog, which) -> {
                    switch (which) {
                        case 0:
                            // 从相册选择
                            selectFromGallery();
                            break;
                        case 1:
                            // 拍照
                            takePhoto();
                            break;
                        case 2:
                            // 使用默认头像
                            useDefaultAvatar();
                            break;
                    }
                })
                .show();
    }

    private void selectFromGallery() {
        // 检查权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 使用新的媒体权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) 
                    != PackageManager.PERMISSION_GRANTED) {
                permissionLauncher.launch(Manifest.permission.READ_MEDIA_IMAGES);
            } else {
                openImagePicker();
            }
        } else {
            // Android 13以下使用READ_EXTERNAL_STORAGE权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) 
                    != PackageManager.PERMISSION_GRANTED) {
                permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
            } else {
                openImagePicker();
            }
        }
    }
    
    /**
     * 打开图片选择器
     */
    private void openImagePicker() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        imagePickerLauncher.launch(Intent.createChooser(intent, "选择图片"));
    }
    
    /**
     * 处理选择的图片
     * @param imageUri 选择的图片URI
     */
    private void handleSelectedImage(Uri imageUri) {
        try {
            // 先显示选择的图片到界面
            Glide.with(this)
                    .load(imageUri)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .placeholder(R.drawable.cat)
                    .error(R.drawable.cat)
                    .into(ivAvatar);
            
            // 显示上传进度
            Toast.makeText(this, "正在上传头像...", Toast.LENGTH_SHORT).show();
            
            // 上传图片到服务器
            uploadImageToServer(imageUri);
            
        } catch (Exception e) {
            Log.e(TAG, "处理选择的图片时出错", e);
            Toast.makeText(this, "图片处理失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 上传图片到服务器
     * @param imageUri 图片URI
     */
    private void uploadImageToServer(Uri imageUri) {
        try {
            // 将URI转换为File临时对象
            File imageFile = createFileFromUri(imageUri);
            if (imageFile == null) {
                Toast.makeText(this, "图片文件处理失败", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 创建RequestBody
            RequestBody requestFile = RequestBody.create(
                    imageFile,
                    MediaType.parse("image/*")
            );
            
            // 创建MultipartBody.Part
            MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", imageFile.getName(), requestFile);
            
            // 创建directory参数
            RequestBody directoryPart = RequestBody.create("member/user", MediaType.parse("text/plain"));
            
            // 调用上传接口
            RetrofitClient.getInstance().getApiService().uploadFile(filePart, directoryPart)
                    .enqueue(new Callback<CommonResult<String>>() {
                        @Override
                        public void onResponse(Call<CommonResult<String>> call, Response<CommonResult<String>> response) {
                            // 检查Activity是否还活着
                            if (isDestroyed() || isFinishing()) {
                                Log.w(TAG, "Activity已销毁，跳过上传回调处理");
                                // 仍然需要清理临时文件
                                if (imageFile.exists()) {
                                    imageFile.delete();
                                }
                                return;
                            }
                            
                            if (response.isSuccessful() && response.body() != null) {
                                CommonResult<String> result = response.body();
                                if (result.isSuccess() && result.getData() != null) {
                                    // 上传成功，获取文件URL
                                    String fileUrl = result.getData();
                                    
                                    // 使用服务器返回的URL更新头像显示
                                    updateAvatarWithUrl(fileUrl);
                                    
                                    // 保存文件URL到用户信息
                                    saveAvatarUrl(fileUrl);
                                    
                                    Toast.makeText(UserInfoActivity.this, "头像上传成功", Toast.LENGTH_SHORT).show();
                                    Log.d(TAG, "头像上传成功，URL: " + fileUrl);
                                    
                                } else {
                                    Log.w(TAG, "文件上传失败: " + result.getMsg());
                                    Toast.makeText(UserInfoActivity.this, "头像上传失败: " + result.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Log.w(TAG, "文件上传网络请求失败");
                                Toast.makeText(UserInfoActivity.this, "头像上传失败", Toast.LENGTH_SHORT).show();
                            }
                            
                            // 清理临时文件
                            if (imageFile.exists()) {
                                imageFile.delete();
                            }
                        }
                        
                        @Override
                        public void onFailure(Call<CommonResult<String>> call, Throwable t) {
                            // 检查Activity是否还活着
                            if (isDestroyed() || isFinishing()) {
                                Log.w(TAG, "Activity已销毁，跳过上传失败回调处理");
                                // 仍然需要清理临时文件
                                if (imageFile.exists()) {
                                    imageFile.delete();
                                }
                                return;
                            }
                            
                            Log.e(TAG, "文件上传网络请求失败", t);
                            Toast.makeText(UserInfoActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                            
                            // 清理临时文件
                            if (imageFile.exists()) {
                                imageFile.delete();
                            }
                        }
                    });
            
        } catch (Exception e) {
            Log.e(TAG, "上传图片到服务器时出错", e);
            Toast.makeText(this, "图片上传失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 从URI创建临时文件
     * @param uri 图片URI
     * @return 临时文件
     */
    private File createFileFromUri(Uri uri) {
        try {
            // 获取内容解析器
            ContentResolver contentResolver = getContentResolver();
            
            // 从URI获取原始文件名
            String originalFileName = getFileNameFromUri(uri);
            
            // 如果无法获取原始文件名，则使用默认文件名
            if (originalFileName == null || originalFileName.isEmpty()) {
                originalFileName = "temp_avatar_" + System.currentTimeMillis() + ".jpg";
            } else {
                // 如果原始文件名没有扩展名，添加.jpg扩展名
                if (!originalFileName.toLowerCase().contains(".")) {
                    originalFileName = originalFileName + ".jpg";
                }
            }
            
            File tempFile = new File(getCacheDir(), originalFileName);
            
            // 从URI读取数据并写入临时文件
            InputStream inputStream = contentResolver.openInputStream(uri);
            if (inputStream != null) {
                FileOutputStream outputStream = new FileOutputStream(tempFile);
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                
                outputStream.close();
                inputStream.close();
                
                Log.d(TAG, "临时文件创建成功: " + originalFileName);
                return tempFile;
            }
        } catch (Exception e) {
            Log.e(TAG, "创建临时文件失败", e);
        }
        return null;
    }
    
    /**
     * 从URI获取文件名
     * @param uri 文件URI
     * @return 文件名，如果无法获取则返回null
     */
    private String getFileNameFromUri(Uri uri) {
        String fileName = null;
        
        try {
            // 尝试从URI查询文件名
            if ("content".equals(uri.getScheme())) {
                // 对于content://类型的URI，查询DISPLAY_NAME
                Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                if (cursor != null) {
                    try {
                        if (cursor.moveToFirst()) {
                            int displayNameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                            if (displayNameIndex != -1) {
                                fileName = cursor.getString(displayNameIndex);
                            }
                        }
                    } finally {
                        cursor.close();
                    }
                }
            } else if ("file".equals(uri.getScheme())) {
                // 对于file://类型的URI，直接从路径获取文件名
                String path = uri.getPath();
                if (path != null) {
                    fileName = new File(path).getName();
                }
            }
            
            // 清理文件名，移除特殊字符
            if (fileName != null) {
                fileName = fileName.replaceAll("[^\\w\\.\\-]", "_");
            }
            
            Log.d(TAG, "从URI获取到文件名: " + fileName);
            
        } catch (Exception e) {
            Log.e(TAG, "从URI获取文件名失败", e);
        }
        
        return fileName;
    }
    
    /**
     * 使用URL更新头像显示
     * @param avatarUrl 头像URL
     */
    private void updateAvatarWithUrl(String avatarUrl) {
        // 检查Activity是否还活着，避免在Activity销毁后使用Glide
        if (isDestroyed() || isFinishing()) {
            Log.w(TAG, "Activity已销毁或正在销毁，跳过头像更新");
            return;
        }
        
        try {
            Glide.with(this)
                    .load(avatarUrl)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .placeholder(R.drawable.cat)
                    .error(R.drawable.cat)
                    .into(ivAvatar);
        } catch (Exception e) {
            Log.e(TAG, "更新头像时出错", e);
        }
    }
    
    /**
     * 保存头像URL到用户信息
     * @param avatarUrl 头像URL
     */
    private void saveAvatarUrl(String avatarUrl) {
        // 获取当前用户信息并更新头像URL
        AppMemberUserInfoRespVO userInfo = UserInfoManager.getUserInfo(this);
        if (userInfo == null) {
            userInfo = new AppMemberUserInfoRespVO();
        }
        userInfo.setAvatar(avatarUrl);
        UserInfoManager.saveUserInfo(this, userInfo);
    }

    private void takePhoto() {
        // 检查相机权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) 
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, 
                    new String[]{Manifest.permission.CAMERA}, 
                    PERMISSION_REQUEST_CODE);
        } else {
            openCamera();
        }
    }
    
    /**
     * 打开相机
     */
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            cameraLauncher.launch(intent);
        } else {
            Toast.makeText(this, "未找到相机应用", Toast.LENGTH_SHORT).show();
        }
    }

    private void useDefaultAvatar() {
        // 显示默认头像
        ivAvatar.setImageResource(R.drawable.cat);
        Toast.makeText(this, "正在设置默认头像...", Toast.LENGTH_SHORT).show();
        
        // 创建默认头像的URI并复用现有的上传方法
        Uri defaultAvatarUri = createUriFromResource(R.drawable.cat);
        if (defaultAvatarUri != null) {
            uploadImageToServer(defaultAvatarUri);
        } else {
            Toast.makeText(this, "默认头像文件处理失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 从drawable资源创建URI
     * @param resourceId 资源ID
     * @return URI对象
     */
    private Uri createUriFromResource(int resourceId) {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            // 创建临时文件
            File tempFile = new File(getCacheDir(), "default_avatar_" + System.currentTimeMillis() + ".png");
            
            // 从资源读取数据并写入临时文件
            inputStream = getResources().openRawResource(resourceId);
            outputStream = new FileOutputStream(tempFile);
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            
            Log.d(TAG, "从资源创建临时文件成功: " + tempFile.getName());
            
            // 返回文件URI
            return Uri.fromFile(tempFile);
            
        } catch (Exception e) {
            Log.e(TAG, "从资源创建URI失败", e);
        } finally {
            // 清理资源
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                Log.e(TAG, "关闭流时出错", e);
            }
        }
        return null;
    }

    private void showGenderDialog() {
        new AlertDialog.Builder(this)
                .setTitle("选择性别")
                .setSingleChoiceItems(genderOptions, selectedGender, null)
                .setPositiveButton("确定", (dialog, which) -> {
                    selectedGender = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                    tvGender.setText(genderOptions[selectedGender]);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void showDatePicker() {
        // 解析当前生日
        String currentBirthday = tvBirthday.getText().toString();
        String[] dateParts = currentBirthday.split("-");
        
        int year = Integer.parseInt(dateParts[0]);
        int month = Integer.parseInt(dateParts[1]) - 1; // 月份从0开始
        int day = Integer.parseInt(dateParts[2]);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, selectedYear, selectedMonth, selectedDay) -> {
                    calendar.set(selectedYear, selectedMonth, selectedDay);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                    tvBirthday.setText(sdf.format(calendar.getTime()));
                },
                year, month, day
        );

        // 设置最大日期为今天
        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
        
        // 设置最小日期为1900年
        Calendar minDate = Calendar.getInstance();
        minDate.set(1900, 0, 1);
        datePickerDialog.getDatePicker().setMinDate(minDate.getTimeInMillis());

        datePickerDialog.show();
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，打开相机
                openCamera();
            } else {
                Toast.makeText(this, "需要相机权限才能拍照", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    /**
     * 保存用户信息到服务器
     * @param userInfo 用户信息
     */
    private void saveUserInfoToServer(AppMemberUserInfoRespVO userInfo) {
        // 创建更新请求参数
        AppMemberUserUpdateReqVO updateRequest = new AppMemberUserUpdateReqVO();
        updateRequest.setAvatar(userInfo.getAvatar());
        updateRequest.setNickname(userInfo.getNickname());
        updateRequest.setSex(userInfo.getSex());
        updateRequest.setBirthday(userInfo.getBirthday());
        
        Log.d(TAG, "开始保存用户信息到服务器: " + updateRequest.toString());
        
        // 显示保存进度提示
        Toast.makeText(this, "正在保存用户信息...", Toast.LENGTH_SHORT).show();
        
        // 调用API更新用户信息
        RetrofitClient.getInstance().getApiService().updateUserInfo(updateRequest)
                .enqueue(new Callback<CommonResult<Boolean>>() {
                    @Override
                    public void onResponse(Call<CommonResult<Boolean>> call, Response<CommonResult<Boolean>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            CommonResult<Boolean> result = response.body();
                            if (result.isSuccess() && result.getData() != null && result.getData()) {
                                // 保存成功
                                Log.d(TAG, "用户信息保存到服务器成功");
                                Toast.makeText(UserInfoActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                                
                                // 设置返回结果为成功，并返回上一页
                                setResult(RESULT_OK);
                                finish();
                            } else {
                                // 保存失败，显示错误信息
                                String errorMsg = result.getMsg() != null ? result.getMsg() : "保存失败";
                                Log.w(TAG, "用户信息保存到服务器失败: " + errorMsg);
                                Toast.makeText(UserInfoActivity.this, "保存失败: " + errorMsg, Toast.LENGTH_SHORT).show();
                                
                                // 虽然服务器保存失败，但本地已保存，提示用户
                                Toast.makeText(UserInfoActivity.this, "信息已保存到本地", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            // 网络请求失败
                            Log.w(TAG, "用户信息保存网络请求失败，响应码: " + response.code());
                            Toast.makeText(UserInfoActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                            Toast.makeText(UserInfoActivity.this, "信息已保存到本地", Toast.LENGTH_SHORT).show();
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<CommonResult<Boolean>> call, Throwable t) {
                        // 网络连接失败
                        Log.e(TAG, "用户信息保存网络连接失败", t);
                        Toast.makeText(UserInfoActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                        Toast.makeText(UserInfoActivity.this, "信息已保存到本地", Toast.LENGTH_SHORT).show();
                    }
                });
    }


} 